<template>
  <div class="home">
    <div class="room-header">
      <h1>聊天室</h1>
      <el-button type="danger" @click="logout">退出</el-button>
    </div>

    <el-card class="chat-list">
      <ul>
        <li v-for="item in msgList" :key="item.id">
          <p>
            <span>{{ item.username }}</span>
            <span>{{ item.dataTime }}</span>
          </p>
          <p>消息：{{ item.msg }}</p>
        </li>
      </ul>
    </el-card>

    <div class="send-box">
      <el-input type="text" placeholder="请输入聊天内容" v-model="msg" />
      <el-button type="primary" :disabled="isSend" @click="sendMsg">发送</el-button>
    </div>
  </div>
</template>

<script>
const ws = new WebSocket("ws://localhost:8000")

export default {
  name: "Home",
  data() {
    return {
      msg: "",
      username: "",
      msgList: [],
    }
  },

  computed: {
    isSend() {
      return this.msg.trim().length === 0
    },
  },

  created() {
    this.username = localStorage.getItem("username")
    if (!this.username) {
      this.$router.push("/login")
    }

    ws.addEventListener("open", this.handleWsOpen.bind(this), false)

    ws.addEventListener("close", this.handleWsClose.bind(this), false)

    ws.addEventListener("error", this.handleWsError.bind(this), false)

    ws.addEventListener("message", this.handleWsMessage.bind(this), false)
  },

  methods: {
    logout() {
      localStorage.clear()
      this.$message.success("退出成功")
      this.$router.push("/login")
    },

    sendMsg() {
      const msg = this.msg.trim()
      if (!msg) return
      ws.send(
        JSON.stringify({
          id: new Date().getTime(),
          username: this.username,
          dateTime: new Date().getTime(),
          msg,
        })
      )
      this.msg = ""
    },

    handleWsOpen(e) {
      console.log("open", e)
    },
    handleWsClose(e) {
      console.log("close", e)
    },
    handleWsError(e) {
      console.log("error", e)
    },
    handleWsMessage({ data }) {
      const obj = JSON.parse(data)
      this.msgList.push(obj)
    },
  },
}
</script>

<style lang="scss" scoped>
.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    margin: 0 0 10px;
  }
}

.el-card {
  width: 500px;
  height: 500px;
  margin-bottom: 10px;
}

.send-box {
  display: flex;

  .el-input {
    margin-right: 20px;
  }
}
</style>
